import 'package:flutter/material.dart';

class DataTableDemo extends StatefulWidget {
  const DataTableDemo({super.key});

  @override
  State<DataTableDemo> createState() => _DataTableDemoState();
}

class _DataTableDemoState extends State<DataTableDemo> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('DataTableDemo'),
        elevation: 0,
      ),
      body: LayoutBuilder(
        builder: (BuildContext context, BoxConstraints constraints) {
          final screenWidth = MediaQuery.of(context).size.width;
          final isNarrowScreen = screenWidth < 600; // 定义临界宽度阈值，可根据需求调整

          // 响应式列定义
          List<DataColumn> responsiveColumns = [
            const DataColumn(label: Text('姓名')),
            const DataColumn(label: Text('年龄')),
            const DataColumn(label: Text('性别')),
            if (!isNarrowScreen) const DataColumn(label: Text('地址')),
            if (!isNarrowScreen) const DataColumn(label: Text('电话')),
          ];

          // 响应式行数据
          List<DataRow> responsiveRows = [
            DataRow(cells: [
              const DataCell(Text('张三')),
              const DataCell(Text('18')),
              const DataCell(Text('男')),
              if (!isNarrowScreen) const DataCell(Text('北京')),
              if (!isNarrowScreen) const DataCell(Text('123456789')),
            ]),
            DataRow(
              cells: [
                const DataCell(Text('李四')),
                const DataCell(Text('19')),
                const DataCell(Text('女')),
                if (!isNarrowScreen) const DataCell(Text('上海')),
                if (!isNarrowScreen) const DataCell(Text('987654321')),
              ],
            ),
          ];

          return Container(
            padding: const EdgeInsets.all(8.0),
            child: DataTable(
              columns: responsiveColumns,
              rows: responsiveRows,
            ),
          );
        },
      ),
    );
  }
}